#include "httpserverhandler.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>

using namespace stefanfrings;

HttpServerHandler::HttpServerHandler(QObject *parent)
    : HttpRequestHandler(parent),
      attendService(new AttendService()),
      employeeService(new EmployeeService()),
      attendanceRulesService(new AttendanceRulesService()),
      faceFeatureTool(FaceFeatureTool::getInstance()),
      attendanceChecker(new AttendanceChecker(attendanceRulesService,attendService)),
      userService(new UserService())
{}

void HttpServerHandler::service(HttpRequest &request, HttpResponse &response)
{
    // 先原子增加总请求数
    m_totalRequests.fetchAndAddOrdered(1);

    // 再原子增加活跃连接数
    m_activeConnections.fetchAndAddOrdered(1);

    QString path = request.getPath();

    if (path == "/api/server_status") {
        handleServerStatus(response);
    }
    else if (path == "/api/health_check") {
        // 健康检查接口也加锁保证稳定性
        QMutexLocker locker(&m_statusMutex);
        QJsonObject health;
        health["status"] = "ok";
        health["timestamp"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        health["total_requests"] = static_cast<int>(m_totalRequests.load());

        QJsonDocument doc(health);
        QByteArray responseData = doc.toJson(QJsonDocument::Compact);

        response.setHeader("Content-Type", "application/json");
        response.write(responseData, true);
    }
    else if (path == "/api") {
        response.write("Server is running", true);
    }
    else if (path == "/api/attend/list" && request.getMethod() == "GET")
    {
        handleGetAttendList(request, response);
    }
    else if (path == "/api/attend/add" && request.getMethod() == "POST")
    {
        handleAddAttendRecord(request, response);
    }
    else if (path == "/api/employee/register" && request.getMethod() == "POST")
    {
        handleRegisterEmployee(request, response);
    }
    else if(path == "/api/attendance_rules/by_name" && request.getMethod() == "GET")
    {
        handleGetAttendanceRulesByName(request, response);
    }
    else if (path == "/api/attendance_rules/by_name" && request.getMethod() == "POST")
    {
        handleUpdateAttendanceRulesByName(request, response);
    }
    else if (path == "/api/employee/by_name" && request.getMethod() == "GET")
    {
        handleGetEmployeesByName(request, response);
    }
    else if (path == "/api/attend/by_employee_id" && request.getMethod() == "GET")
    {
        handleGetAttendRecordsByEmployeeId(request, response);
    }
    else if (path == "/api/attend/leave" && request.getMethod() == "POST")
    {
        handleLeaveRequest(request, response);
    }
    else if (path == "/api/attend/leaveByTimeRange" && request.getMethod() == "POST") {
        handleLeaveByTimeRange(request, response);
    }
    else if (path == "/api/user/login" && request.getMethod() == "POST") {
        handleLogin(request, response);
    }
    else {
        response.setStatus(404, "Not Found");
        response.write("Interface not found", true);
    }

    // 最后原子减少活跃连接数
    m_activeConnections.fetchAndSubOrdered(1);

    //        // 设置响应格式为JSON
    //        response.setHeader("Content-Type", "application/json; charset=utf-8");

    //        // 根据请求路径分发处理
    //        QByteArray path = request.getPath();

    //        else
    //        {
    //            // 404 Not Found
    //            response.setStatus(404, "Not Found");
    //            response.write("{\"error\":\"Not found\"}", true);
    //        }
    //        m_activeConnections.fetchAndSubOrdered(1);
}

void HttpServerHandler::handleGetAttendList(HttpRequest &request, HttpResponse &response)
{
    // 调用业务逻辑层获取数据
    QJsonArray result = attendService->getAttendList();
    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleAddAttendRecord(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;

    if (request.getHeader("content-type").startsWith("multipart/form-data"))
    {
        // 获取打卡照片（不再需要employeeId参数）
        QTemporaryFile *attendPhotoFile = request.getUploadedFile("attendPhoto");
        if (!attendPhotoFile)
        {
            result["success"] = false;
            result["error"] = "没有照片数据";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        // 读取照片数据
        attendPhotoFile->open();
        QByteArray attendPhotoData = attendPhotoFile->readAll();
        attendPhotoFile->close();

        // 查询数据库中所有员工的照片和ID（新增方法）
        QList<QPair<QString, QByteArray>> allEmployees = employeeService->getAllEmployeePhotos();
        if (allEmployees.isEmpty())
        {
            result["success"] = false;
            result["error"] = "系统中没有员工数据";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }
        QString employeeId;

        // 与所有员工照片进行比对，找到匹配的员工
        QString matchedEmployeeId;
        bool matched = false;
        foreach (auto &employee, allEmployees)
        {
            employeeId = employee.first;
            QByteArray employeePhotoData = employee.second;

            if (faceFeatureTool->faceComparison(employeePhotoData, attendPhotoData))
            {
                matchedEmployeeId = employeeId;
                matched = true;
                break; // 找到第一个匹配的员工即停止
            }
        }

        if (!matched)
        {
            result["success"] = false;
            result["error"] = "未找到匹配的员工";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        // 后续逻辑使用匹配到的员工ID继续处理
        QDateTime currentDateTime = QDateTime::currentDateTime();
        QString currentDateStr = currentDateTime.toString("yyyy-MM-dd");
        QString currentTimeStr = currentDateTime.toString("HH:mm:ss");
        QString currentDateTimeStr = currentDateTime.toString("yyyy-MM-dd HH:mm:ss");

        QJsonObject applicableRule = attendanceChecker->getApplicableRule(matchedEmployeeId);
        if (applicableRule.isEmpty())
        {
            result["error"] = "未获取到有效的考勤规则";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        QTime splitTime = QTime::fromString(applicableRule["split_time"].toString(), "HH:mm:ss");
        QString checkType = (currentDateTime.time() <= splitTime) ? "in" : "out";
        QString employeeIdinfo = QString("员工[%1] ").arg(employeeId);

        if (!attendanceChecker->isCheckInWithinAllowedTime(matchedEmployeeId, currentDateTime))
        {
            result["error"] = checkType == "in" ? "不在签到时间范围内" : "不在签退时间范围内";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        if (attendanceChecker->isDuplicateCheckIn(matchedEmployeeId, currentDateTime, checkType))
        {
            result["error"] = checkType == "in" ?employeeIdinfo + "今日已签到，无需重复打卡" :employeeIdinfo + "今日已签退，无需重复打卡";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        QJsonObject attendStatus = attendService->getAttendStatusByEmployeeIdAndDate(matchedEmployeeId, currentDateStr);
        if (!attendStatus.isEmpty()) {
            QString signIn = attendStatus["signInStatus"].toString();
            QString signOut = attendStatus["signOutStatus"].toString();

            // 上午请假或全天请假时，禁止上午签到
            if ((signIn == "上午请假" || signIn == "全天请假") && checkType == "in") {
                result["error"] = employeeIdinfo + "已请假，无需签到";
                response.write(QJsonDocument(result).toJson(), true);
                return;
            }

            // 下午请假或全天请假时，禁止下午签退
            if ((signOut == "下午请假" || signOut == "全天请假") && checkType == "out") {
                result["error"] = employeeIdinfo + "已请假，无需签退";
                response.write(QJsonDocument(result).toJson(), true);
                return;
            }
        }

        // 继续处理正常打卡流程
        bool processSuccess = attendanceChecker->processCheckInOut(matchedEmployeeId, currentDateTimeStr);
        if (!processSuccess)
        {
            result["error"] = "考勤记录处理失败";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        attendStatus = attendService->getAttendStatusByEmployeeIdAndDate(matchedEmployeeId, currentDateStr);
        if (attendStatus.isEmpty())
        {
            result["success"] = false;
            result["error"] = "考勤记录存储成功，但查询状态失败";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        QString message;
        if(attendStatus["checkType"].toString() == "in")
        {
            message =employeeIdinfo + QString("签到成功-状态[%1]").arg(attendStatus["currentStatus"].toString());
        } else {
            message =employeeIdinfo + QString("签退成功-状态[%1]").arg(attendStatus["currentStatus"].toString());
        }

        result["success"] = true;
        result["message"] = message;
        response.write(QJsonDocument(result).toJson(), true);
    }
    else
    {
        result["success"] = false;
        result["error"] = "Unsupported content type (need multipart/form-data)";
        response.write(QJsonDocument(result).toJson(), true);
    }
}

void HttpServerHandler::handleRegisterEmployee(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;

    // 判断是否为multipart/form-data请求（用于上传照片）
    if (request.getHeader("content-type").startsWith("multipart/form-data"))
    {
        // 获取表单字段
        QString employeeId = request.getParameter("employeeId");
        QString name = request.getParameter("name");
        QString department = request.getParameter("department");
        QString position = request.getParameter("position");

        // 获取上传的照片文件
        QTemporaryFile *photoFile = request.getUploadedFile("photo");
        if (!photoFile)
        {
            result["success"] = false;
            result["error"] = "No photo uploaded";
            response.write(QJsonDocument(result).toJson(), true);
            return;
        }

        // 读取照片数据
        photoFile->open();
        QByteArray photoData = photoFile->readAll();
        photoFile->close();

        // 调用业务逻辑层注册
        bool success = employeeService->registerEmployee(employeeId, name, department, position, photoData);

        if (success)
        {
            result["success"] = true;
            result["message"] = "Employee registered successfully";
        }
        else
        {
            result["success"] = false;
            result["error"] = "Registration failed";
        }
    }
    else
    {
        result["success"] = false;
        result["error"] = "Unsupported content type";
    }

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleGetAttendanceRulesByName(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;
    // 获取查询参数中的规则名称（支持模糊查询）
    QString ruleName = request.getParameter("rule_name");

    if (ruleName.isEmpty())
    {
        result["success"] = false;
        result["error"] = "规则名称参数不能为空";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 调用业务层查询规则（假设存在AttendanceRuleService）
    // 这里使用ruleService示例，实际项目中需根据实际类名调整
    QJsonArray rules = attendanceRulesService->getRulesByName(ruleName);

    if (rules.isEmpty())
    {
        result["success"] = true;
        result["message"] = "未找到匹配的考勤规则";
        result["data"] = QJsonArray(); // 返回空数组
    }
    else
    {
        result["success"] = true;
        result["count"] = rules.size();
        result["data"] = rules;
    }

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleUpdateAttendanceRulesByName(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(request.getBody());

    if (jsonDoc.isNull())
    {
        result["success"] = false;
        result["error"] = "无效的JSON格式";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    QJsonObject reqData = jsonDoc.object();

    // 校验必填参数
    if (!reqData.contains("rule_name") || reqData["rule_name"].toString().isEmpty())
    {
        result["success"] = false;
        result["error"] = "规则名称不能为空";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 解析时间参数
    auto parseTime = [](const QJsonValue& value) -> QTime {
        if (value.isString()) {
            return QTime::fromString(value.toString(), "HH:mm:ss");
        }
        return QTime();
    };

    QString rule_name = reqData["rule_name"].toString();
    QTime work_start = parseTime(reqData["work_start"]);
    QTime work_end = parseTime(reqData["work_end"]);
    QTime checkin_start = parseTime(reqData["checkin_start"]);
    QTime checkout_end = parseTime(reqData["checkout_end"]);
    QTime split_time = parseTime(reqData["split_time"]);

    // 校验时间有效性
    if (!work_start.isValid() || !work_end.isValid() ||
            !checkin_start.isValid() || !checkout_end.isValid())
    {
        result["success"] = false;
        result["error"] = "时间格式无效，需使用HH:mm:ss";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 调用业务层更新规则
    bool updateSuccess = attendanceRulesService->updateRulesByRuleName(
                rule_name, work_start, work_end,split_time, checkin_start, checkout_end
                );

    if (updateSuccess)
    {
        result["success"] = true;
        result["message"] = QString("考勤规则「%1」更新成功").arg(rule_name);
    }
    else
    {
        result["success"] = false;
        result["error"] = QString("更新失败，未找到规则「%1」或数据错误").arg(rule_name);
    }

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleGetEmployeesByName(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;

    // 获取查询参数
    QString name = request.getParameter("name");
    if (name.isEmpty())
    {
        result["success"] = false;
        result["error"] = "员工姓名参数不能为空";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 调用业务层方法查询
    QJsonArray employees = employeeService->getEmployeesByName(name);

    // 构造响应
    result["success"] = true;
    result["count"] = employees.size();
    result["data"] = employees;

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleGetAttendRecordsByEmployeeId(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;

    // 获取查询参数
    QString employeeId = request.getParameter("employee_id");
    if (employeeId.isEmpty())
    {
        result["success"] = false;
        result["error"] = "员工号参数不能为空";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 调用业务层方法查询
    QJsonArray records = attendService->getAttendRecordsByEmployeeId(employeeId);

    // 构造响应
    result["success"] = true;
    result["count"] = records.size();
    result["data"] = records;

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleLeaveRequest(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;
    QJsonObject params = QJsonDocument::fromJson(request.getBody()).object();

    // 解析请求参数
    QString employeeId = params["employeeId"].toString();
    QString recordDate = params["recordDate"].toString();
    QString leaveTypeStr = params["leaveType"].toString();
    qDebug() << employeeId << " " <<  recordDate << " " << leaveTypeStr;
    // 参数校验（保持不变）
    if (employeeId.isEmpty() || recordDate.isEmpty() || leaveTypeStr.isEmpty()) {
        result["success"] = false;
        result["error"] = "参数不完整";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 检查员工是否存在（保持不变）
    if (employeeService->getEmployeePhoneById(employeeId).isEmpty()) {
        result["success"] = false;
        result["error"] = "员工不存在";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 转换请假类型（保持不变）
    AttendanceChecker::CheckStatus leaveType;
    if (leaveTypeStr == "morning") {
        leaveType = AttendanceChecker::CheckStatus::LEAVE_MORNING;
    } else if (leaveTypeStr == "afternoon") {
        leaveType = AttendanceChecker::CheckStatus::LEAVE_AFTERNOON;
    } else if (leaveTypeStr == "full") {
        leaveType = AttendanceChecker::CheckStatus::LEAVE_FULL;
    } else {
        result["success"] = false;
        result["error"] = "无效的请假类型";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 检查是否已有**有效打卡记录（排除请假状态）**
    QJsonObject attendStatus = attendService->getAttendStatusByEmployeeIdAndDate(employeeId, recordDate);
    bool hasValidCheckInOut = false;
    if (!attendStatus.isEmpty()) {
        QString signIn = attendStatus["signInStatus"].toString();
        QString signOut = attendStatus["signOutStatus"].toString();

        // 关键修改：排除请假状态，仅当存在正常/迟到/早退/缺勤的打卡记录时才判定为有效
        bool isSignInValid = (signIn != "缺卡" && signIn != "上午请假" && signIn != "全天请假");
        bool isSignOutValid = (signOut != "缺卡" && signOut != "下午请假" && signOut != "全天请假");
        hasValidCheckInOut = isSignInValid || isSignOutValid;
    }

    if (hasValidCheckInOut) {
        result["success"] = false;
        result["error"] = "已有打卡记录，无法请假";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 检查是否重复请假
    bool isDuplicateLeave = false;
    QString duplicateType;
    if (!attendStatus.isEmpty()) {
        QString signIn = attendStatus["signInStatus"].toString();
        QString signOut = attendStatus["signOutStatus"].toString();

        if (signIn == "全天请假" || signOut == "全天请假") {
            isDuplicateLeave = true;
            duplicateType = "全天";
        } else if (leaveType == AttendanceChecker::CheckStatus::LEAVE_MORNING && signIn == "上午请假") {
            isDuplicateLeave = true;
            duplicateType = "上午";
        } else if (leaveType == AttendanceChecker::CheckStatus::LEAVE_AFTERNOON && signOut == "下午请假") {
            isDuplicateLeave = true;
            duplicateType = "下午";
        }
    }

    if (isDuplicateLeave) {
        result["success"] = false;
        result["error"] = QString("已申请%1请假，无法重复申请").arg(duplicateType);
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 处理请假（保持不变）
    bool success = attendanceChecker->processLeave(employeeId, recordDate, leaveType);

    if (success) {
        result["success"] = true;
        result["message"] = "请假申请成功";
    } else {
        result["success"] = false;
        result["error"] = "请假处理失败，请稍后重试";
    }

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleLeaveByTimeRange(HttpRequest &request, HttpResponse &response)
{
    QJsonObject result;
    QJsonObject params = QJsonDocument::fromJson(request.getBody()).object();

    // 解析请求参数
    QString employeeId = params["employeeId"].toString();
    QString startDate = params["startDate"].toString();
    QString endDate = params["endDate"].toString();
    QString startTimeType = params["startTimeType"].toString(); // "morning"或"afternoon"
    QString endTimeType = params["endTimeType"].toString();     // "morning"或"afternoon"

    // 参数校验
    if (employeeId.isEmpty() || startDate.isEmpty() || endDate.isEmpty() ||
            (startTimeType != "morning" && startTimeType != "afternoon") ||
            (endTimeType != "morning" && endTimeType != "afternoon")) {
        result["success"] = false;
        result["error"] = "参数错误：员工ID、日期或时间段类型不正确";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 日期格式校验
    QDate start = QDate::fromString(startDate, "yyyy-MM-dd");
    QDate end = QDate::fromString(endDate, "yyyy-MM-dd");
    if (!start.isValid() || !end.isValid() || start > end) {
        result["success"] = false;
        result["error"] = "日期格式错误或开始日期晚于结束日期";
        response.write(QJsonDocument(result).toJson(), true);
        return;
    }

    // 处理请假时间段
    bool allSuccess = true;
    QDate currentDate = start;
    while (currentDate <= end) {
        QString currentDateStr = currentDate.toString("yyyy-MM-dd");

        // 处理同一天内的请假
        if (currentDate == start && currentDate == end) {
            if (startTimeType == "morning" && endTimeType == "afternoon") {
                // 全天请假
                allSuccess &= attendanceChecker->processLeave(
                            employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_FULL);
            } else if (startTimeType == "morning") {
                // 上午开始且当天结束 → 全天请假（上午+下午均请假）
                allSuccess &= attendanceChecker->processLeave(
                            employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_FULL);
            } else {
                // 下午开始且当天结束 → 仅下午请假，上午保持原状态（无记录则缺卡）
                QJsonObject status = attendService->getAttendStatusByEmployeeIdAndDate(employeeId, currentDateStr);
                QString signInStatus = status["signInStatus"].toString();

                if (signInStatus.isEmpty() || signInStatus == "缺卡") {
                    // 上午无记录 → 保持缺卡，仅更新下午请假
                    allSuccess &= attendService->updateLeaveStatus(
                                employeeId, currentDateStr,
                                "缺卡",  // 上午保持缺卡
                                attendanceChecker->statusToString(AttendanceChecker::CheckStatus::LEAVE_AFTERNOON)
                                );
                } else {
                    // 上午有记录 → 保持原状态，更新下午请假
                    allSuccess &= attendanceChecker->processLeave(
                                employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_AFTERNOON);
                }
            }
        }
        // 处理开始日期（非结束日）
        else if (currentDate == start) {
            if (startTimeType == "morning") {
                // 上午开始 → 全天请假（上午+下午均请假）
                allSuccess &= attendanceChecker->processLeave(
                            employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_FULL);
            } else {
                // 下午开始 → 仅下午请假，上午保持原状态（无记录则缺卡）
                QJsonObject status = attendService->getAttendStatusByEmployeeIdAndDate(employeeId, currentDateStr);
                QString signInStatus = status["signInStatus"].toString();

                if (signInStatus.isEmpty() || signInStatus == "缺卡") {
                    // 上午无记录 → 保持缺卡
                    allSuccess &= attendService->updateLeaveStatus(
                                employeeId, currentDateStr,
                                "缺卡",  // 上午保持缺卡
                                attendanceChecker->statusToString(AttendanceChecker::CheckStatus::LEAVE_AFTERNOON)
                                );
                } else {
                    // 上午有记录 → 保持原状态
                    allSuccess &= attendanceChecker->processLeave(
                                employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_AFTERNOON);
                }
            }
        }
        // 处理结束日期（非开始日）
        else if (currentDate == end) {
            if (endTimeType == "morning") {
                // 上午结束 → 仅上午请假，下午保持原状态（无记录则缺卡）
                QJsonObject status = attendService->getAttendStatusByEmployeeIdAndDate(employeeId, currentDateStr);
                QString signOutStatus = status["signOutStatus"].toString();

                if (signOutStatus.isEmpty() || signOutStatus == "缺卡") {
                    // 下午无记录 → 保持缺卡
                    allSuccess &= attendService->updateLeaveStatus(
                                employeeId, currentDateStr,
                                attendanceChecker->statusToString(AttendanceChecker::CheckStatus::LEAVE_MORNING),
                                "缺卡"  // 下午保持缺卡
                                );
                } else {
                    // 下午有记录 → 保持原状态
                    allSuccess &= attendanceChecker->processLeave(
                                employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_MORNING);
                }
            } else {
                // 下午结束 → 全天请假（上午+下午均请假）
                allSuccess &= attendanceChecker->processLeave(
                            employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_FULL);
            }
        }
        // 处理中间日期（全天请假）
        else {
            allSuccess &= attendanceChecker->processLeave(
                        employeeId, currentDateStr, AttendanceChecker::CheckStatus::LEAVE_FULL);
        }

        if (!allSuccess) break;
        currentDate = currentDate.addDays(1);
    }

    if (allSuccess) {
        result["success"] = true;
        result["message"] = "请假申请已提交";
    } else {
        result["success"] = false;
        result["error"] = "部分日期请假处理失败";
    }

    response.write(QJsonDocument(result).toJson(), true);
}
void HttpServerHandler::handleLogin(HttpRequest &request, HttpResponse &response) {
    QJsonObject result;
    QByteArray body = request.getBody();
    QJsonDocument doc = QJsonDocument::fromJson(body);
    QJsonObject params = doc.object();

    QString username = params["username"].toString();
    QString password = params["password"].toString();

    if (userService->verifyLogin(username, password)) {
        result["success"] = true;
        result["message"] = "登录成功";
    } else {
        result["success"] = false;
        result["message"] = "账号或密码错误";
    }

    response.write(QJsonDocument(result).toJson(), true);
}

void HttpServerHandler::handleServerStatus(HttpResponse& response)
{
    QMutexLocker locker(&m_statusMutex);

    // 使用固定格式的JSON，避免动态内容
    QJsonObject status;
    status["status"] = "running";
    status["timestamp"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    status["total_requests"] = static_cast<int>(m_totalRequests.load());
    status["active_connections"] = static_cast<int>(m_activeConnections.load());
    status["server_version"] = "SmartCheck v1.0";

    // 使用紧凑且固定的JSON格式
    QJsonDocument doc(status);
    QByteArray responseData = doc.toJson(QJsonDocument::Compact);

    // QtWebApp 正确的头部设置方式
    response.setStatus(200, "OK");
    response.setHeader("Content-Type", "application/json; charset=UTF-8");
    response.setHeader("Content-Length", QByteArray::number(responseData.size()));

    // 写入响应体
    response.write(responseData, true);

    qDebug() << "📊 服务器状态查询 - 总请求:" << m_totalRequests.load()
             << "活跃连接:" << m_activeConnections.load()
             << "响应长度:" << responseData.size();
}
